package com.cms.cmsbackend.service;

import com.cms.cmsbackend.controller.ArticleController;
import com.cms.cmsbackend.mapper.ArticleMapper;
import com.cms.cmsbackend.mapper.CategoryMapper;
import com.cms.cmsbackend.pojo.Article;
import com.cms.cmsbackend.pojo.Category;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
   private CategoryMapper categoryMapper;
    public void save(Article article){
        //判断栏目是否存在
        Category category=categoryMapper.selectByPrimaryKey(article.getCategory_id());
        if (category == null){
            //栏目id在数据库里面不存在
            throw new RuntimeException(" 栏目编号不存在 ");
        }else {
            articleMapper.insert(article);
        }
    }

    public PageInfo findByPage(int page, int size, String author, String title){
        /*
        如果作者和标题都为空 查询所有
        如果作者和标题都不为空 查询任意一个中包含的信息
        如果作者为空 标题不为空
        标题为空 作者不为空
         */
        PageHelper.startPage(page,size);
        author = author == null? "" : author;
        title = title == null? "" : title;
        Example example=new Example(Article.class);
        example.createCriteria().
                andLike("author","%"+author+"%").
                andLike("title","%"+title+"%");
        List<Article> articles=articleMapper.selectAll();
        PageInfo pageInfo=new PageInfo<>(articles);
        return pageInfo;
    }

    public void remove(int id){
        articleMapper.deleteByPrimaryKey(id);
    }

    public void batchrem(int[] ids){
        for (int id:ids){
            articleMapper.deleteByPrimaryKey(id);
        }
    }

    public Article choose(int id){
     Article article=articleMapper.selectByPrimaryKey(id);
     return article;
    }
    public void updata(Article article){
        articleMapper.updateByPrimaryKey(article);
    }
}
